<template>
  <div class="app-container">
    <!-- 面包屑导航 -->
    <div style="padding-bottom: 20px;">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>系统管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 条件查询   -->
    <el-form :inline="true" :model="query" size="mini">
      <el-form-item >
        <el-input size="small" v-model.trim="query.userName" placeholder="输入用户名"></el-input>
      </el-form-item>
      <el-form-item >
        <el-input size="small" v-model.trim="query.phone" placeholder="输入手机号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" icon="el-icon-search" type="primary" @click="queryData">查询</el-button>
        <el-button size="small" icon="el-icon-refresh" @click="reload">重置</el-button>
      </el-form-item>
    </el-form>
    <!--  列表数据  -->
    <el-table :data="list" border style="width: 100%" stripe>
      <el-table-column align="center" label="序号" width="120" type="index"></el-table-column>
      <el-table-column align="center" prop="avatar" label="头像" width="80">
        <template slot-scope="scope">
          <el-image :src="scope.row.avatar" style="width: 50px;height: 50px;border-radius: 50%"></el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="userName" label="用户名"></el-table-column>
      <el-table-column align="center" prop="sex" label="性别" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sex === 0" type="danger">女</el-tag>
          <el-tag v-if="scope.row.sex === 1" type="success">男</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="phone" label="手机号" width="180"></el-table-column>
      <el-table-column align="center" prop="email" label="邮箱地址" width="200" ></el-table-column>
      <el-table-column align="center" prop="status" label="账号状态" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0" type="danger">锁定</el-tag>
          <el-tag v-if="scope.row.status === 1" type="success">正常</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="createTime" label="创建时间" width="200" >
        <template slot-scope="scope">
          <!-- 格式化日期 -->
          {{getFormat(scope.row.createTime)}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="430px">
        <template slot-scope="scope">
          <el-button icon="el-icon-setting" type="success" size="mini" @click="handleEdit(scope.row.userId)">编辑</el-button>
          <el-button v-if="scope.row.status === 1" icon="el-icon-lock" type="warning" size="mini" @click="handleLock(scope.row.userId, 0)">锁定</el-button>
          <el-button v-if="scope.row.status === 0" icon="el-icon-unlock" type="warning" size="mini" @click="handleLock(scope.row.userId, 1)">解锁</el-button>
          <el-button icon="el-icon-edit" type="info" size="mini" @click="handleRole(scope.row.userId, scope.row.userName)">分配角色</el-button>
          <el-button icon="el-icon-document-delete" type="danger" size="mini" @click="handleDel(scope.row.userId)">删除</el-button>
<!--          <el-button icon="el-icon-edit-outline" type="primary" size="mini" @click="handlePass(scope.row.userId)">修改密码</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="query.current"
      :page-sizes="[10, 20, 50]"
      :page-size="query.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="query.total">
    </el-pagination>

    <!-- 新增或者编辑弹窗 -->
    <edit :title="edit.title" :visiable="edit.visiable" :formData="edit.formData" :remoteClose="remoteClose"/>

    <!-- 设置角色弹窗 -->
    <role :formData="role.formData"  :userRoleIds="role.roleIds" :visiable="role.visiable" :remoteClose="remoteClose"/>

  </div>
</template>

<script>
import userApi from '@/api/user';
import Edit from './edit';
import {dateFormat} from '@/utils/date';
import Role from './role';
import Pwd from './pwd.vue';
export default {
  name:'User',
  components:{
     Edit,
     Role,
    // Pwd
  },
  data(){
    return{
      list:[],       //列表数据
      page:{
        current: 0,   // 当前页码
        size: 20,     // 每页大小
        total: 0      // 总记录数
      },
      query: {
        current: 0,   // 当前页码
        size: 20,     // 每页大小
        total: 0,      // 总记录数
        userName: '',   // 用户名
        phone: '',  // 手机号码
      },      // 查询条件
      edit:{
        title: '',
        visiable: false,
        formData: {}
      },
      role:{
        visiable: false,  // 弹出设置角色窗口
        roleIds: [],      // 封装当前用户所拥有的的角色id
        formData: {
          userId: null,   // 当前用户的用户id
          userName: null,     // 当前用户的用户名称
        }
      },
      pwd:{
        title: '',
        visiable: false,
        userId: ''
      },
    }
  },

  created(){
    // 用户信息分页查询
    this.fetchData();
  },

  methods:{
    // 用户信息分页查询
    fetchData(){
      userApi.getAllUser(this.query).then(response => {
        if(response.code === 200){
          this.list = response.data.list;
        }
      })
    },

    // 编辑
    handleEdit(id){
      // 根据用户id查询用户信息
      userApi.getById(id).then(response => {
        if(response.code === 200){
          this.edit.title = '编辑';
          this.edit.visiable = true;
          this.edit.formData = response.data;
        }
      })
    },

    // 删除
    handleDel(id){
      this.$confirm('确认删除这条记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求
        userApi.deleteUserById(id).then(response => {
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 1500
            });
          } else if (response.code === 306) {
            this.$notify.error({
              title: '错误',
              message: '您没有操作权限，请联系管理员',
              duration: 1500
            });
          } else {
            this.$notify.error({
              title: '错误',
              message: '系统异常，请稍后再试',
              duration: 1500
            });
          }
          // 刷新列表
          this.fetchData();
        })
      }).catch(() => {
        // 取消删除
      });
    },

    // 设置角色
    handleRole(id, name){
      // 查询用户拥有的角色id 传递给子组件
      userApi.getUserRoleIdsByUserId(id).then(response => {
        if(response.code === 200){
          // console.log("roleIds="+response.data)
          this.role.roleIds = response.data;
          this.role.formData.userName = name;
          this.role.formData.userId = id;
          this.role.visiable = true;
        }
      })
    },

    // 条件查询
    queryData(){
      this.page.current = 1;
      this.fetchData();
    },

    // 重置
    reload(){
      this.query = {};
      this.fetchData();
    },

    // val 是切换之后的每页显示多少条
    handleSizeChange(val){
      this.page.size = val;
      this.fetchData();
    },

    // 当页码改变后触发此方法 val是当前点击（或输入）的页码
    handleCurrentChange(val){
      this.page.current = val;
      this.fetchData();
    },

    // 子组件会触发该方法来关闭窗口
    remoteClose(){
      this.edit.formData = {};
      this.role.formData = {};
      this.edit.visiable = false;
      this.role.visiable = false;
      this.role.roleIds = [];
      this.fetchData();
    },

    // 格式化日期
    getFormat(date){
      return dateFormat(date);
    },

    // 锁定和解锁
    handleLock(userId, status) {
      const data = {
        userId, status
      };
      userApi.lock(data).then(resp => {
        if (resp.code === 200) {
          this.$notify({
            title: '成功',
            message: '操作成功',
            type: 'success',
            duration: 1500
          });
          this.fetchData();
        }
      })
    }

  },
}
</script>

<style scoped>

</style>
